#include "NetworkCommonFunction.h"
#include "volumeplan.h"
#include "pathconst.h"

#include <boost/scoped_array.hpp>
#include <QDomDocument>
#include <QFile>
#include <QDebug>

bool VolumePlanHandler(int socket, int commandLength)
{
	qDebug()<<"Receive volume plan command";

	unsigned long volumeListXmlLength;

	if(!getFourByte(socket, volumeListXmlLength))
	{
		qDebug()<<"Get Volume list xml file length error";
		return false;
	}

	char* xmlBuffer = new char[volumeListXmlLength];
	boost::scoped_array<char> xmlBufferContainer(xmlBuffer);

	if(!receiveData(socket, xmlBuffer, volumeListXmlLength))
	{
		qDebug()<<"Get Volume xml data error";
		return false;
	}

	QDomDocument document;
	document.setContent(QByteArray(xmlBuffer, volumeListXmlLength));
	QDomElement rootElement = document.firstChildElement();
	int windowNo = rootElement.attribute("WindowNo").toInt();

	QString volumeListPath = VolumeListPath(windowNo);

	QFile volumePlanFile(volumeListPath);
	if(!volumePlanFile.open(QFile::WriteOnly))
	{
		qDebug()<<"Open volume list file to write error";
	}
	else
	{
		QTextStream stream(&volumePlanFile);
		document.save(stream, 4);
	}
	volumePlanFile.close();

	VolumePlan volumePlan(volumeListPath);
	volumePlan.doCommand();

	return true;
}
